// miniprogram/pages/find/index.js
const app = getApp();
var userInfo;
const DB = wx.cloud.database()
var util = require('../../utils/util.js');
var that;
var testNum=6230001;
Page({

  data: {
    userInfo: {},
    laiyuan_yaoqing: 1,
    show_tip: true,
    yizan: false
  },
  // 提问
  quizinput(e) {
    console.log(e.detail.value)
    this.setData({
      quizVal: e.detail.value
    })
  },
  // 评论
  cominput(e) {
    console.log(e.detail.value)
    this.setData({
      commVal: e.detail.value
    })
  },
  is_login(){
    if(!wx.getStorageSync('userInfo')){
      wx.reLaunch({
        url: '/pages/login/login',
      })
    }
  },
  // 提交提问
  upQuiz() {
    this.is_login()
    let data = {
      txt: this.data.quizVal,
      time: new Date().getTime(),
      a: wx.getStorageSync('userInfo')._openid,
      b: this.data.userInfo._openid,
      status: 0,
      hande: wx.getStorageSync('userInfo').userInfoDetail.hande,
      nicheng: wx.getStorageSync('userInfo').userInfoDetail.nicheng,
    }
    DB.collection('quiz_list').add({
      data: data,
      success: function (res) {
        that.add_tiwenNum()
        that.getQuizList(that.data.userInfo.openid)
        wx.showToast({
          title: '已提交提问',
          icon: 'none'
        })
        that.setData({
          quizVal: ''
        })
        console.log('提问成功-res', res)
      }
    })
  },
  // 提交评论
  upCom() {
    this.is_login()
    var _id = this.data.userInfo._id;
    DB.collection('user').doc(_id).get().then(res => {
      let val = res.data.zan_openid;
      let commentData; 
      let obj = {
        txt: this.data.commVal,
        time: new Date().getTime(),
        hande: this.data.userInfo.userInfoDetail.hande||this.data.userInfo.avatarUrl,
        nicheng: this.data.userInfo.userInfoDetail.nicheng||this.data.userInfo.nickName,
      }
      if (res.data.comment && res.data.comment.length > 0) {
        commentData = res.data.comment
        commentData.push(obj)
      } else {
        commentData = [obj]
      }
      DB.collection('user').doc(_id).update({
        data: {
          comment: commentData
        },
        success: function (res) {
          that.setData({
            commVal: ''
          })
          console.log('评论成功-res', res)
        }
      })
    })
  },
  // 点赞
  zan() {
    this.is_login()
    console.log('d22idaaa')

    if (this.data.yizan) return
    console.log('didaaa')
    var _id = this.data.userInfo._id;
    var my_openid = wx.getStorageSync('userInfo')._openid;
    DB.collection('user').doc(_id).get().then(res => {
      let val = res.data.zan_openid;
      if (val && val.length > 0) {
        console.log('val', val, my_openid)
        if (val.indexOf(my_openid) == -1) {
          val.push(my_openid)
        } else {
          return
        }
      } else {
        val = [my_openid]
      }
      console.log('2222222222222222', val)
      DB.collection('user').doc(_id).update({
        data: {
          zan_openid: val
        },
        success: function (res) {
          console.log('res', res)
          that.setData({
            yizan: true
          })
        }
      })
    })
  },
  yaoqing() {
    this.is_login()
    getApp().sendMsg()
    wx.cloud.callFunction({
      name: "invitation",
      data: {
        b: this.data.userInfo._openid,
        b_img: this.data.userInfo.userInfoDetail.hande,
        b_name: this.data.userInfo.userInfoDetail.nicheng,
        a: wx.getStorageSync('userInfo')._openid,
        a_img: wx.getStorageSync('userInfo').userInfoDetail.hande,
        a_name: wx.getStorageSync('userInfo').userInfoDetail.nicheng,
        status: 0,
      },
      success(res) {
        console.log('res', res.result._id)
        if (res.result == "已邀请，不可重复邀请") {
          console.log('已邀请，不可重复邀请', res)
          wx.showToast({
            title: '已邀请，不可重复邀请',
            icon: "none"
          })
        } else {
          wx.showToast({
            title: '邀请成功',
          })
          var data = {
            openid: that.data.userInfo._openid,
            page: "pages/user_detail/user_detail?openid=" + wx.getStorageSync('userInfo').openid + '&id=' + res.result._id,
            time2: util.formatTime(new Date()),
            thing8: wx.getStorageSync('userInfo').userInfoDetail.nicheng || "",
            templateId: "SQ7U_NT4gGV_msdgTpPiARDFIQIv1ECFxCYFBP_apkg",
            miniprogramState: "developer"
          }
          console.log('邀请成功', data)
          // developer为开发版；trial为体验版；formal为正式版；默认为正式版
          wx.cloud.callFunction({
            name: "sendMsg",
            data: data,
            success(res) {
              console.log('邀请好友成功-------------', res.result)
            },
            fail(err) {
              console.log('邀请好友失败-------------', err)

            }
          })
        }
      },
      fail(res) {
        console.log('邀请失败', res)
      }
    })
  },
  fangda(e) {
    console.log(e)
    var current = e.target.dataset.src;
    wx.previewImage({
      current: current, // 当前显示图片的http链接 
      urls: this.data.userInfo.userInfoDetail.live_phone // 需要预览的图片http链接列表 
    })
  },
  jieshou(item) {
    this.is_login()
    var date = util.formatTime(new Date())

    DB.collection('invitation_list').doc(this.data.id)
      .get().then(ress => {
        console.log('=-', ress)
        var {
          a,
          a_img,
          a_name,
          b,
          b_img,
          b_name
        } = ress.data
        let data = {
          a,
          a_img,
          a_name,
          b,
          b_img,
          b_name,
          date,
          msgList: [],
          a_zaixian: false,
          b_zaixian: false
        }
        console.log('user——————————', data)
        DB.collection('friends').add({
          data: data,
          success: function (res) {
            wx.reLaunch({
              url: '/pages/friends_list/friends_list' // 这里是要跳转的路径
            })
          }
        })
      })



  },
  jujue(e) {
    this.is_login()
    DB.collection('invitation_list').doc(this.data.id).update({
      data: {
        status: 2
      },
      success: function (res) {
        that.setData({
          laiyuan_yaoqing: 0
        })
      }
    })
  },
  onLoad: function (options) {
    this.setData({
      time: new Date().getTime()
    })

    // options={
    //   openid:'odRMY0QKotP0SAqoOfDpT3VY_MtI',
    //   id:"5efaaa445ef1b2ab003cb3973ec0631c"
    // }
    console.log('options', wx.getStorageSync('userInfo')._openid)

    that = this
    let userInfo;
    let whereData = {};
    // laiyuan_yaoqing 1 默认， 2 邀请 3 分享
    
    if(options.share){
      whereData = {
        _openid: options.openid,
      }
      this.setData({
        laiyuan_yaoqing: 3
      })
    }

    if (options.id) {
      that.getQuizList(options.openid)
      whereData = {
        _id: options.id,
      }
      this.setData({
        laiyuan_yaoqing: 2
      })
    }
    if(!options.share&&!options.openid) {
      userInfo = wx.getStorageSync('seeuserInfo')
      that.getQuizList(userInfo._openid)
      whereData = {
        _openid: userInfo._openid,
      }
      this.setData({
        laiyuan_yaoqing: 1
      })
    }
    console.log('1111111',whereData)
    DB.collection('user').where(whereData)
      // .get().then(res=>{console.log('===',res.data)})
      .watch({
        onChange: function (ress) {
          console.log('22222222',whereData, ress.docs[0].nickName)
          if (ress.docs[0].zan_openid && ress.docs[0].zan_openid.indexOf(wx.getStorageSync('userInfo')._openid) != -1) {
            that.setData({
              yizan: true
            })
          }
          var userInfo = ress.docs[0];
          var myUserInfo = wx.getStorageSync('userInfo');
          userInfo.userInfoDetail.hande = userInfo.userInfoDetail.live_phone[0]
          myUserInfo.userInfoDetail.hande = myUserInfo.userInfoDetail.live_phone[0]
          that.setData({
            userInfo,
            myUserInfo 
          })
          if(!myUserInfo||!userInfo){
            console.log('333333333',myUserInfo, userInfo)
            that.onLoad(options)
          }
          if(ress.docs[0].userInfoDetail.sex ==wx.getStorageSync('userInfo').userInfoDetail.sex){
            that.setData({
              yixing:false
            })
          }else{
            that.setData({
              yixing:true
            })
          }
        },
        onError: function (err) {
          console.log('444444444',err)
          that.onLoad(options)
          console.error('----------------error', err)
        }
      })

      this.add_seeNum()
      this.getCharacterList()
  },

  
  //用户授权登录登录
  loginGetUserInfo: function (e) {
    getApp().sendMsg()

    var that = this;
    let iv = e.detail.iv
    if (e.detail.iv == undefined) { //如果用户拒绝授权
    } else {
      wx.getUserInfo({ //调用授权api，获取用户信息
        success: function (res) {
          var userInfo = res.userInfo
          wx.cloud.callFunction({
            name: "openId",
            data: {},
            success(res) {
              var openid = res.result.openid;
              userInfo.openid = openid;

              DB.collection('user').get({
                  success: function (res) {
                    console.log('=============>', res.data)
                    var is_my =false;
                    res.data.forEach(item=>{
                      if(item._openid == openid){
                        is_my=item
                        wx.setStorageSync('userInfo', item)
                      }
                    })
                    if (is_my){
                      that.setData({
                        login_status:true
                      })
                    } else {
                      getApp().AppUserAdd()
                    }
                  }
                })
            },
            fail(res) {
              console.log('333333333失败', res)
            }
          })
        }
      })
    }
  },

  // 获取三观列表
  getCharacterList() {
    DB.collection('character_list')
      .get({
        success: function (res) {
          let list = res.data
          console.log('list:', list)
          // list = getRandomArrayElements(list, 3)
          console.log('随机的list:', list)
          // list.forEach((value, i) => {
          // });
          that.setData({
            quest: list
          })
        },
        fail: function (err) {
          console.log('err', err)
        }
      })
  },
  onShow() {
    let seeIdx =wx.getStorageSync('see_list').indexOf(wx.getStorageSync('seeuserInfo')._openid);
    let seeuserInfo_list =wx.getStorageSync('seeuserInfo_list')
    seeuserInfo_list[seeIdx] = wx.getStorageSync('seeuserInfo')
    wx.setStorageSync('seeuserInfo_list', seeuserInfo_list)
    if(wx.getStorageSync('userInfo')){
      this.setData({
        login_status:true
      })
    }else{
      console.log('1111111111111',wx.getStorageSync('userInfo'))
      this.setData({
        login_status:false
      })
      return
    }
  },
  // 提问数量自增
  add_tiwenNum() {
    const _ = app.DB.command
    app.DB.collection('user').doc(this.data.userInfo._id).update({
      data: {
        tiwenNum: _.inc(1)
      },
      success: function (res) {
        console.log(res.data)
      }
    })
  },
  // 查看数量自增
  add_seeNum() {
    const _ = app.DB.command
    if (this.data.userInfo._id) {
      console.log('this.data.userInfo._id',this.data.userInfo._id)
      app.DB.collection('user').doc(this.data.userInfo._id).update({
        data: {
          seeNum: _.inc(1)
        },
        success: function (res) {
          console.log(res)
        }
      })
    } else {
      setTimeout(() => {
        this.add_seeNum()
      }, 500);
    }
  },
  // 获取问答列表
  getQuizList(openid) {
    DB.collection('quiz_list').where({
      b: openid
    }).get().then(res => {
      that.setData({
        Quiz: res.data
      })
      console.log(res.data)
    })
  },
  show_tip() {
    var show_tip = !this.data.show_tip
    this.setData({
      show_tip
    })
  },
  shouchang() {
    this.is_login()
    getApp().sendMsg()

    var _openid = this.data.myUserInfo._openid
    DB.collection('shouchang').where({
        _openid: _openid,
      })
      .get({
        success: function (res) {
          if (res.data.length > 0) {
            if (res.data[0].shouchang_list.indexOf(that.data.userInfo._openid) == -1) {
              res.data[0].shouchang_list.push(that.data.userInfo._openid)
              DB.collection('shouchang').doc(wx.getStorageSync('userInfo').shouchang_id).update({
                data: {
                  shouchang_list: res.data[0].shouchang_list
                }
              })
              wx.showToast({
                title: '收藏成功',
              })
            } else {
              wx.showToast({
                title: '已在收藏列表',
              })
            }

          } else {
            var data = {
              openid: that.data.myUserInfo._openid,
              shouchang_list: [that.data.userInfo._openid]
            }
            console.log('收藏信息2', data)
            DB.collection('shouchang').add({
              data: data,
              success: function (res) {
                console.log('成功', res)
                var userInfo = wx.getStorageSync('userInfo');
                userInfo.shouchang_id = res._id;
                wx.setStorageSync('userInfo', userInfo)

                DB.collection('user').doc(wx.getStorageSync('userInfo')._id).update({
                  data: {
                    shouchang_id: res._id
                  }
                })
                wx.showToast({
                  title: '收藏成功',
                })
              }
            })
          }
        }
      })

  },

  nav_detail() {
    wx.navigateTo({
      url: '/pages/user_detail/user_detail',
    })
  },
  
})